<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
      <CommonContainer title="基础信息">
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="模版名称" prop="templateName">
              <el-input style="width: 70%" v-model.trim="form.templateName" placeholder="请输入模版名称" maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模版类型" prop="templateType">
              <el-select style="width: 70%" v-model="form.templateType" placeholder="请选择模版类型" disabled>
                <el-option label="租赁模版" :value="1"></el-option>
                <!--                                <el-option label="续租模版" :value="2"></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="form.templateClassification==1">
            <el-form-item label="客户类型" prop="customersTypeArray">
              <el-select style="width: 70%" v-model="form.customersTypeArray" multiple placeholder="请选择客户类型">
                <el-option v-for="dict in dict.type.customer_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="8" v-if="form.templateClassification==2||form.templateClassification==3">
            <el-form-item label="关联客户" prop="customerNames">
              <div @click="chooseCustomer">
                <el-input style="width: 70%" v-model="form.customerNames" placeholder="请选择客户" readonly></el-input>
              </div>
            </el-form-item>
          </el-col>
          <!--          <el-col v-if="form.templateClassification==2" :span="8">-->
          <!--            <el-form-item label="公司标准模版" prop="companyStandardTemplateName">-->
          <!--              <div @click="chooseCompanyStandardTemplate">-->
          <!--                <el-input style="width: 70%" v-model="form.companyStandardTemplateName" placeholder="请选择公司标准模版" readonly></el-input>-->
          <!--              </div>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <el-col :span="8">
            <el-form-item label="产品方案" prop="planId">
              <el-select style="width: 70%" v-model="form.planId" placeholder="请选择产品方案">
                <el-option v-for="(item,index) in planList" :key="item.id" :label="item.schemeName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="新/旧车" prop="newOrOldCarsArray">
              <el-select style="width: 70%" v-model="form.newOrOldCarsArray" multiple placeholder="请选择新/旧">
                <el-option v-for="dict in dict.type.new_or_old_cars" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否带驾" prop="leadingTheDriverArray">
              <el-select style="width: 70%" v-model="form.leadingTheDriverArray" multiple placeholder="请选择是否带驾">
                <el-option v-for="dict in dict.type.business_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="说明">
              <el-input style="width: 70%" type="textarea" placeholder="请输入说明" v-model="form.templateRemark" maxlength="500" :rows="5" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件">
              <div class="flex">
                <image-common :up-type="2" info="上传附件" is-show-tip :file-type="fileType" :limit="20" :fileSize="50" v-model="form.templateAnnex"></image-common>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </CommonContainer>

      <CommonContainer title="合同约定" v-if="form.templateType==1">
        <div>
          <el-row :gutter="20">
            <el-col :span="8">

              <div class="agreedItem">
                <div class="titleInfo flex-row-center-sb">
                  <span class="ruleTitle">逾期还车</span>
                  <e-switch v-model="form.overdue"></e-switch>
                </div>
                <el-form-item prop="overdueParam" :rules="{
                                                             required: true,
                                                             message: '请输入逾期还车规则',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, value, callback, form.overdue)
                                                           }">
                  <div class="agreedContent flex-row-center">
                    逾期日租金:原日租金
                    <el-input style="width: 100px;margin: 0 8px"
                              v-model="form.overdueParam"
                              onkeyup="value=value.replace(/[^0-9.]/g,'')"
                              @input="checkOverdueParam"
                              @blur="overdueParamBlur"
                              :disabled="form.overdue==2?true:false"></el-input>
                    %
                  </div>
                </el-form-item>
              </div>

              <div class="agreedItem">
                <div class="titleInfo flex-row-center-sb">
                  <span class="ruleTitle">异地还车</span>
                  <e-switch v-model="form.offsite"></e-switch>
                </div>
                <el-form-item prop="offsiteParam" :rules="{
                                                             required: true,
                                                             message: '请输入异地还车规则',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, value, callback, form.offsite)
                                                           }">
                  <div class="agreedContent flex-row-center">
                    单价:
                    <el-input style="width: 100px;margin: 0 8px"
                              v-model="form.offsiteParam"
                              :disabled="form.offsite==2?true:false"
                              onkeyup="value=value.replace(/[^0-9.]/g,'')"
                              @input="checkOffsiteParam"
                              maxlength="9"
                    ></el-input>
                    元/公里
                  </div>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="agreedItem">
                <div class="titleInfo flex-row-center-sb">
                  <span class="ruleTitle">滞纳金</span>
                  <e-switch v-model="form.lateFee"></e-switch>
                </div>
                <el-form-item prop="lateFeeParam" :rules="{
                                                             required: true,
                                                             message: '请输入滞纳金计费规则',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, value, callback, form.lateFee)
                                                           }">
                  <div class="agreedContent flex-row-center">
                    计费规则:逾期金额的
                    <el-input style="width: 100px;margin: 0 8px"
                              v-model="form.lateFeeParam"
                              :disabled="form.lateFee==2?true:false"
                              onkeyup="value=value.replace(/[^0-9.]/g,'')"
                              @input="checkLateFeeParam"
                              @blur="lateFeeParamBlur"
                    ></el-input>
                    %
                  </div>
                </el-form-item>
              </div>
              <div class="agreedItem">
                <div class="titleInfo flex-row-center-sb">
                  <span class="ruleTitle">超公里费</span>
                  <e-switch v-model="form.overmileageFee"></e-switch>
                </div>
                <el-form-item prop="overmileageFeeParam" :rules="{
                                                             required: true,
                                                             message: '请输入超公里费计费规则',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, value, callback, form.overmileageFee)
                                                           }">
                  <div class="agreedContent flex-row-center">
                    单价:
                    <el-input style="width: 100px;margin: 0 8px"
                              v-model="form.overmileageFeeParam"
                              :disabled="form.overmileageFee==2?true:false"
                              onkeyup="value=value.replace(/[^0-9.]/g,'')"
                              @input="checkOvermileageFee"
                              maxlength="9"
                    ></el-input>
                    元/公里
                  </div>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="agreedItem" style="height: 228px">
                <p class="titleInfo flex-row-center-sb">
                  <span class="ruleTitle">逾期规则(租金)</span>
                  <e-switch v-model="form.overdueRules"></e-switch>
                </p>
                <div class="agreedContent" style="margin-top: 35px">
                  <el-radio-group v-model="form.overdueRulesType" :disabled="form.overdueRules==2?true:false" @change="changeOverdueRulesType">

                    <el-radio :label="1">
                      <el-form-item prop="overdueRulesParam1" :rules="{
                                                             required: true,
                                                             message: '请输入逾期规则',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData1(rule, value, callback, form.overdueRules, 1)
                                                           }">
                        <div class="flex-row-center">
                          逾期规则:超
                          <el-input style="width: 80px;margin: 0 8px"
                                    v-model="form.overdueRulesParam1"
                                    :disabled="form.overdueRules==2?true:false"
                                    onkeyup="value=value.replace(/[^\d||/.]/g,'')"
                                    oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value==0&&value!=''){value=1}"
                                    maxlength="7"
                          ></el-input>
                          自然日未付款
                        </div>
                      </el-form-item>
                    </el-radio>

                    <el-radio :label="2" style="margin-top: 15px">
                      <el-form-item prop="overdueRulesParam2" :rules="{
                                                             required: true,
                                                             message: '请输入逾期规则',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData2(rule, value, callback, form.overdueRules, 2)
                                                           }">
                        <div class="flex-row-center">
                          逾期规则:次期
                          <el-input style="width: 80px;margin: 0 8px"
                                    v-model="form.overdueRulesParam2"
                                    :disabled="form.overdueRules==2?true:false"
                                    onkeyup="value=value.replace(/[^\d||/.]/g,'')"
                                    oninput="if(value){value=value.replace(/[^\d]/g,'')}  if(value>28){value=28} if(value==0&&value!=''){value=1}"
                                    :maxlength="2"
                                    :minlength="1"
                          ></el-input>
                          日前未付款
                        </div>
                      </el-form-item>
                    </el-radio>

                  </el-radio-group>


                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">

              <div class="agreedItem" style="height: auto">
                <div class="titleInfo flex-row-center-sb">
                  <span class="ruleTitle">提前还车</span>
                  <e-switch v-model="form.earlyReturn"></e-switch>
                </div>
                <div style="padding-bottom: 20px">
                  <el-table
                      :data="form.earlyReturnRules"
                      :header-cell-style="{ background: '#FAFAFA', color: '#000000' }" border :key="isUpdate">
                    <el-table-column
                        align="center"
                        prop="reasonForEarlyReturn"
                        label="提前还车"
                        key="reasonForEarlyReturn"
                        min-width="160">
                      <template v-slot="{row}">
                        <el-form-item style="margin-top: 15px;width: 100%" label-width="0" prop="reasonForEarlyReturn" :rules="{
                                                             required: true,
                                                             message: '请选择提前还车原因',
                                                             trigger: ['blur','change'],
                                                             validator: (rule, value, callback) => validData(rule, row.reasonForEarlyReturn, callback,form.earlyReturn)
                                                           }">
                          <el-select v-model="row.reasonForEarlyReturn" placeholder="请选择提前还车原因" :disabled="form.earlyReturn==2?true:false">
                            <el-option v-for="dict in dict.type.reason_for_early_return" :label="dict.label" :value="parseInt(dict.value)"
                                       :key="dict.value"></el-option>
                          </el-select>
                        </el-form-item>

                      </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="leaseTerm"
                        label="已履行租期(月)"
                        key="leaseTerm"
                        min-width="160">
                      <template v-slot="{row}">
                        <el-form-item style="margin-top: 15px;width: 100%" label-width="0" prop="leaseTerm" :rules="{
                                                             type:'array',
                                                             required: true,
                                                             message: '请输入已履行租期',
                                                             trigger: ['blur','change'],
                                                             validator: (rule, value, callback) => validData(rule, row.leaseTerm, callback, form.earlyReturn)
                                                           }">
                          <input-number-range v-model="row.leaseTerm" separator="/" unit="月" :type="1" @input="changeLeaseTerm(row, $event)"
                                              :disabled="form.earlyReturn==2?true:false"></input-number-range>
                        </el-form-item>


                      </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="liquidatedDamagesScale"
                        label="违约金比例"
                        key="liquidatedDamagesScale"
                        min-width="250">
                      <template v-slot="scope">
                        <el-form-item style="margin-top: 15px;width: 100%" label-width="0" prop="liquidatedDamagesScale" :rules="{
                                                             required: true,
                                                             message: '请输入违约金比例',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, scope.row.liquidatedDamagesScale, callback, form.earlyReturn)
                                                           }">
                          <div class="flex-row-center">
                            剩余未履行租赁期应支付租金总额的
                            <el-input style="width: 80px;margin: 0 8px"
                                      v-model="scope.row.liquidatedDamagesScale"
                                      onkeyup="value=value.replace(/[^0-9.]/g,'')"
                                      @input="event => checkLiquidatedDamagesScale(event, scope.$index)"
                                      @blur="event=>liquidatedDamagesScaleBlur(event, scope.$index)"
                                      :disabled="form.earlyReturn==2?true:false"
                            ></el-input>
                            %
                          </div>
                        </el-form-item>

                      </template>
                    </el-table-column>

                    <el-table-column
                        align="center"
                        prop="fieldDict"
                        label="操作"
                        min-width="50">
                      <template v-slot="{$index}">
                        <i style="color: #1890ff;font-size: 20px" class="el-icon-delete" @click="deleteEarlyReturnRules($index)"></i>
                      </template>
                    </el-table-column>
                    <template v-slot:append>
                      <div class="flex-xy-center" style="height: 30px">
                        <el-button :disabled="form.earlyReturn==2?true:false" type="text" icon="el-icon-plus" @click="addEarlyReturnRules">添加规则</el-button>
                      </div>
                    </template>
                  </el-table>
                </div>
              </div>

            </el-col>
          </el-row>
        </div>
      </CommonContainer>

      <CommonContainer title="合同模版">
        <div style="margin-top: 10px">
          <div class="flex-row-center">
            <el-button type="primary" @click="handleUploadFile">上传附件</el-button>
          </div>
          <div v-if="form.contractAnnex" style="margin-top: 15px">
            <image-common v-model="form.contractAnnex" :up-type="1" :limit="1"></image-common>
          </div>
          <div style="margin: 15px 0">
            <tinymce-editor v-model="form.contractContent" :tag-list="tagList" :key="isUpdate"></tinymce-editor>
          </div>
        </div>
      </CommonContainer>

      <div class="card-wrap flex justify-end card-padding">
        <el-button @click="cancel">取消</el-button>
        <el-button v-loading="saveLoading" type="primary" @click="submitForm">保存</el-button>
        <el-button v-loading="submitLoading" type="primary" @click="commitApproval" v-if="form.approvalStatus==0">提交审批</el-button>
      </div>
    </el-form>
    <select-customer v-if="form.templateClassification>1" ref="selectCustomer" :customer-ids="form.customerIds" @success="selectCustomerSuccess"></select-customer>
    <select-company-template v-if="form.templateClassification==2" ref="selectCompanyTemplate" @success="selectCompanyTemplateSuccess"></select-company-template>
    <el-dialog
        title="附件是否导入合同模板"
        :visible.sync="uploadFileDialogVisible"
        width="30%"
        center>
      <span>注：请上传大小不超过50MB 格式为doc、docx格式的文件</span>
      <span slot="footer" class="flex-row-center-ar">
<!--             <contract-template-upload :upload-type="2" @uploadSuccess="unImportToEditor"></contract-template-upload>-->
             <el-button style="width: 100px; height: 40px; position: relative;" @click="uploadFileDialogVisible=false">取消</el-button>
             <contract-template-upload :upload-type="1" @uploadSuccess="importToEditor"></contract-template-upload>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectCustomer from "@/views/contractTemplate/components/SelectCustomer.vue";
import SelectCompanyTemplate from "@/views/contractTemplate/components/SelectCompanyTemplate.vue";
import InputNumberRange from "@/components/InputNumberRange/index.vue";
import CustomTag from '../components/customTag.vue';
import ContractTemplateEditor from "@/components/Editor/contractTemplateEditor.vue";
import ContractTemplateUpload from "@/components/FileUpload/contractTemplateUpload.vue";
import TinymceEditor from "@/components/TinymceEditor/index.vue";
import * as contractTemplateApi from "@/api/contractTemplate/contractTemplate";
import {planList} from "@/api/contractTemplate/contractTemplate";
import {isEmpty} from "lodash";
import {checkListNumberInput, checkNumberInput} from "@/utils/utils";

export default {
  name: 'AddContractTemplate',
  dicts: ['new_or_old_cars', 'customer_type', 'business_yes_no', 'reason_for_early_return'],
  components: {SelectCustomer, SelectCompanyTemplate, InputNumberRange, CustomTag, ContractTemplateEditor, ContractTemplateUpload, TinymceEditor},
  data() {
    return {
      saveLoading: false,
      submitLoading: false,
      uploadFileDialogVisible: false,
      fileType: ['png', 'jpg', 'jpeg', 'pdf', 'excel', 'doc', 'docx', 'msg'],
      form: {
        templateName: null,
        templateClassification: 1,
        templateType: 1,
        customersType: null,
        customersTypeArray: null,
        planId: null,
        newOrOldCars: null,
        newOrOldCarsArray: null,
        leadingTheDriver: null,
        leadingTheDriverArray: null,
        templateRemark: null,
        templateAnnex: null,//模版附件
        overdue: 1,
        overdueParam: null,
        offsite: 1,
        offsiteParam: null,
        overmileageFee: 1,
        overmileageFeeParam: null,
        lateFee: 1,
        lateFeeParam: null,
        overdueRules: 1,
        overdueRulesType: 1,
        overdueRulesParam: null,
        overdueRulesParam1: null,
        overdueRulesParam2: null,
        earlyReturn: 1,
        earlyReturnRules: [],
        flowId: null,
        approvalStatus: null,
        enablingStatus: null,
        onlyThis: null,
        applicationNo: null,
        contractAnnex: null,//合同附件
        contractParam: null,
        contractContent: null,
        customerIds: null,
        customerNames: null,
        companyStandardTemplate: null,
        companyStandardTemplateName: null,

      },
      rules: {
        templateName: [
          {required: true, message: '请输入模版名称', trigger: 'blur'},
        ],
        templateType: [
          {required: true, message: '请选择模版类型', trigger: 'blur'},
        ],
        customerNames: [
          {required: true, message: '请选择客户', trigger: ["blur", "change"]},
        ],
        customersTypeArray: [
          {required: true, message: '请选择客户类型', trigger: ["blur"]},
        ],
        companyStandardTemplateName: [
          {required: true, message: '请选择公司合同模版', trigger: ["blur", "change"]},
        ],
        planId: [
          {required: true, message: '请选择产品方案', trigger: ["blur"]},
        ],
        newOrOldCarsArray: [
          {required: true, message: '请选择新/旧车', trigger: ["blur"]},
        ],
        leadingTheDriverArray: [
          {required: true, message: '请选择是否带驾', trigger: ["blur"]},
        ]
      },

      tagList: [],
      planList: [],
      isUpdate: Math.random(),
    }
  },
  methods: {
    changeOverdueRulesType(val) {
      this.$refs.form.validateField(['overdueRulesParam1', 'overdueRulesParam2'])
    },
    getPlanList() {
      planList({
        shelveStatus: 1
      }).then(res => {
        this.planList = res.data;
      })
    },
    unImportToEditor(data) {
      this.uploadFileDialogVisible = false
      this.form.contractAnnex = data?.ossId
    },
    importToEditor(data) {
      this.uploadFileDialogVisible = false
      this.form.contractContent = data?.richText
      this.form.contractAnnex = data?.ossId
    },
    //获取合同模版参数
    getContractTemplateParams() {
      contractTemplateApi.contractTemplateParam({
        type: 1
      }).then(res => {
        this.tagList = res.data;
      })
    },
    //合同详情
    getContractTemplateDetail() {
      contractTemplateApi.contractTemplateDetails(this.$route.query.id).then(res => {
        this.form = res.data;
        if (!isEmpty(this.form.customersType)) {
          this.$set(this.form, 'customersTypeArray', this.form.customersType?.split(','))
        }
        if (!isEmpty(this.form.newOrOldCars)) {
          this.$set(this.form, 'newOrOldCarsArray', this.form.newOrOldCars?.split(','))
        }
        if (!isEmpty(this.form.leadingTheDriver)) {
          this.$set(this.form, 'leadingTheDriverArray', this.form.leadingTheDriver?.split(','))
        }
        if (this.form.overdueRulesParam) {
          if (this.form.overdueRulesType == 1) {
            this.$set(this.form, 'overdueRulesParam1', this.form.overdueRulesParam)
          } else if (this.form.overdueRulesType == 2) {
            this.$set(this.form, 'overdueRulesParam2', this.form.overdueRulesParam)
          }
        }
        if (this.form.earlyReturnRules && this.form.earlyReturnRules.length > 0) {
          this.form.earlyReturnRules = this.form.earlyReturnRules.map(item => {
            this.$set(item, 'leaseTerm', [item.minLeaseTerm, item.maxLeaseTerm])
            return item
          })
        }
        if (this.form.templateClassification > 1) {
          if (!this.isNull(this.form.customerIds)) {
            this.form.customerIds = this.form.customerIds?.split(',')
          }
        }
        // this.$forceUpdate()
        console.log('回显数据---', this.form)
      })
    },
    //关联客户
    chooseCustomer() {
      this.$refs.selectCustomer.show()
    },
    //关联客户回调
    selectCustomerSuccess(customers) {
      if (customers && customers.length > 0) {
        let customerIds = [];
        let customerNames = [];
        customers.forEach(item => {
          customerIds.push(item.customerId);
          customerNames.push(item.customerName);
        })
        this.form.customerIds = customerIds;
        this.form.customerNames = customerNames.join(',');
      }
      console.log('当前选中的客户------', customers)
    },
    //选择公司标准模版
    chooseCompanyStandardTemplate() {
      if (!this.isNull(this.form.templateType)) {
        this.$refs.selectCompanyTemplate.show(this.form.templateType)
      } else {
        this.$message.warning('请先选择模版类型')
      }
    },
    // 选择公司合同模版回调=>回显标准模版基础及约定信息
    selectCompanyTemplateSuccess(row) {
      this.form.companyStandardTemplate = row.id;
      this.form.companyStandardTemplateName = row.templateName;
      this.form.planId = row.planId;
      console.log('当前选择的公司合同模版---', row)
      this.getCompanyContractTemplateDetail(row.id);
    },
    //公司标准模版合同详情
    getCompanyContractTemplateDetail(templateId) {
      contractTemplateApi.contractTemplateDetails(templateId).then(res => {
        const data = res.data;
        if (!isEmpty(data.newOrOldCars)) {
          this.$set(this.form, 'newOrOldCarsArray', data?.newOrOldCars?.split(','))
        }
        if (!isEmpty(data.leadingTheDriver)) {
          this.$set(this.form, 'leadingTheDriverArray', data.leadingTheDriver?.split(','))
        }
        this.form.overdue = data?.overdue;
        this.form.overdueParam = data?.overdueParam;
        this.form.offsite = data?.offsite;
        this.form.offsiteParam = data?.offsiteParam;
        this.form.overmileageFee = data?.overmileageFee;
        this.form.overmileageFeeParam = data?.overmileageFeeParam;
        this.form.lateFee = data?.lateFee;
        this.form.lateFeeParam = data?.lateFeeParam;
        this.form.overdueRules = data?.overdueRules;
        if (data.overdueRulesParam) {
          if (data.overdueRulesType == 1) {
            this.$set(this.form, 'overdueRulesParam1', data.overdueRulesParam)
          } else if (data.overdueRulesType == 2) {
            this.$set(this.form, 'overdueRulesParam2', data.overdueRulesParam)
          }
        }
        this.form.earlyReturn = data?.earlyReturn;
        if (data.earlyReturnRules && data.earlyReturnRules.length > 0) {
          this.form.earlyReturnRules = data.earlyReturnRules.map(item => {
            this.$set(item, 'leaseTerm', [item.minLeaseTerm, item.maxLeaseTerm])
            return item
          })
        } else {
          this.form.earlyReturn = []
        }
        //先将富文本中的内容置空,防止数据污染
        this.form.contractContent = null;
        this.form.contractContent = data?.contractContent;
        this.isUpdate = !this.isUpdate;
        console.log('公司标准模版---', this.form)
      })
    },
    addEarlyReturnRules() {
      const ruleObj = {
        reasonForEarlyReturn: null,
        selected: 1,
        minLeaseTerm: null,
        maxLeaseTerm: null,
        liquidatedDamagesScale: null,
        leaseTerm: []
      }
      if (this.form.earlyReturnRules == null) {
        this.form.earlyReturnRules = []
      }
      this.form.earlyReturnRules.push(ruleObj)
    },
    // 删除规则
    deleteEarlyReturnRules(index) {
      this.form.earlyReturnRules.splice(index, 1)
    },
    //合同模版附件上传成功的回调事件
    uploadSuccess(res) {
      this.form.contractContent = res.data;
    },
    // 选择参数
    handleCustomTag() {
      this.$refs.customtag.show();
    },
    handleUploadFile() {
      this.uploadFileDialogVisible = true
    },
    //取消
    cancel() {
      this.$confirm('确认取消吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.back()
      })

    },
    // 保存
    submitForm(type) {
      this.saveLoading = true
      if (this.$route.query.id) {//编辑
        this.formatOtherForm()
        contractTemplateApi.contractTemplateUpdate(this.form).then(res => {
          this.$message.success('编辑成功')
          this.back()
        }).finally((f) => {
          this.saveLoading = false
        })
      } else {//新增
        this.formatOtherForm()
        contractTemplateApi.contractTemplateAdd(this.form).then(res => {
          this.$message.success('新增成功')
          this.back()
        }).finally((f) => {
          this.saveLoading = false
        })
      }

    },
    //提交审批
    commitApproval() {
      let flag = false

      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.isNull(this.form.contractAnnex)) {
            this.$message.error('请上传合同模版附件')
            return
          } else {
            this.submitForApproval()
          }

        }
      })
    },
    submitForApproval() {
      this.formatOtherForm()
      this.submitLoading = true
      contractTemplateApi.submitForApproval(this.form).then(res => {
        this.$message.success('提交审批成功')
        this.back()
      }).finally((f) => {
        this.submitLoading = false
      })
    },
    formatOtherForm() {
      if (this.form.templateClassification == 1) {
        if (this.form.customersTypeArray && this.form?.customersTypeArray?.length > 0) {
          this.form.customersType = this.form?.customersTypeArray?.join(',')
        }
      } else {
        this.form.customersType = null
      }
      if (this.form?.newOrOldCarsArray && this.form?.newOrOldCarsArray?.length > 0) {
        this.form.newOrOldCars = this.form?.newOrOldCarsArray?.join(',')
      }
      if (this.form?.leadingTheDriverArray && this.form?.leadingTheDriverArray?.length > 0) {
        this.form.leadingTheDriver = this.form?.leadingTheDriverArray?.join(',')
      }
      if (this.form.overdueRulesType == 1) {
        this.form.overdueRulesParam = this.form?.overdueRulesParam1
      } else if (this.form.overdueRulesType == 2) {
        this.form.overdueRulesParam = this.form?.overdueRulesParam2
      }

    },
    back() {
      this.$router.back()
    },
    changeLeaseTerm(row, val) {
      row.minLeaseTerm = val[0] ?? null
      row.maxLeaseTerm = val[1] ?? null
    },
    validData(rule, value, callback, switchStatus) {
      console.log('valueother', value)
      if (switchStatus == 1 && rule.required && (!value || (rule.type = 'array' && value.length == 0))) {
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },
    validData1(rule, value, callback, switchStatus, type) {
      console.log('value', value)
      if (switchStatus == 1 && type == this.form.overdueRulesType && rule.required && !value) {
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },
    validData2(rule, value, callback, switchStatus, type) {
      console.log('value', value)
      if (switchStatus == 1 && type == this.form.overdueRulesType && rule.required && !value) {
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },

    //逾期还车输入校验
    checkOverdueParam(event) {
      checkNumberInput(this.form.overdueParam, (newValue) => {
        if (newValue > 10000) {
          this.form.overdueParam = 10000
        } else {
          this.form.overdueParam = newValue
        }

      })
    },
    overdueParamBlur(event){
      const value = event.target.value;
      if(value!=""&&value!=null&&value<0.01){
        this.form.overdueParam = 0.01
      }
    },

    //异地还车规则输入校验
    checkOffsiteParam() {
      checkNumberInput(this.form.offsiteParam, (newValue) => {
        this.form.offsiteParam = newValue
      })
    },

    //滞纳金规则输入校验
    checkLateFeeParam() {
      checkNumberInput(this.form.lateFeeParam, (newValue) => {
        if (newValue > 10000) {
          this.form.lateFeeParam = 10000
        } else {
          this.form.lateFeeParam = newValue
        }

      })
    },
    lateFeeParamBlur(event) {
      const value = event.target.value;
      if(value!=""&&value!=null&&value<0.01){
        this.form.lateFeeParam = 0.01
      }
    },

    //超公里费规则输入校验
    checkOvermileageFee() {
      checkNumberInput(this.form.overmileageFeeParam, (newValue) => {
        this.form.overmileageFeeParam = newValue
      })
    },

    //校验违约金比例
    checkLiquidatedDamagesScale(event, index) {
      const newValue = checkListNumberInput(event);
      if (newValue > 10000) {
        this.form.earlyReturnRules[index].liquidatedDamagesScale = 10000
      } else {
        this.form.earlyReturnRules[index].liquidatedDamagesScale = newValue
      }
    },

    liquidatedDamagesScaleBlur(event, index){
      const value = event.target.value;
      if(value!=""&&value!=null&&value<0.01){
        this.form.earlyReturnRules[index].liquidatedDamagesScale = 0.01
      }
    },

  },
  mounted() {
    this.getContractTemplateParams()
    this.getPlanList()
    const query = this.$route.query;
    if (query) {
      if (query.id) {
        this.$nextTick(() => {
          this.getContractTemplateDetail()
        })
      }
      if (query.templateClassification) {
        this.form.templateClassification = query.templateClassification
      }
    }

  },

}
</script>

<style lang="scss" scoped>
.agreedItem {
  box-sizing: border-box;
  padding: 15px 20px 0;
  border-radius: 6px;
  border: 1px solid #DADADA;
  margin-bottom: 20px;
  height: 106px;
  font-size: 14px;
  color: #333333;

  .titleInfo {
    margin-bottom: 15px;

    .ruleTitle {
      font-weight: bold;

      &::before {
        content: '*';
        color: #F5222D;
        position: relative;
        top: 2px;
        margin-right: 4px;
      }
    }
  }

  .agreedContent {
    //margin-top: 15px;
  }
}


::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

.el-form-item {
  margin-bottom: 15px;
  //width: 70%;
}

::v-deep .el-radio {
  color: #606266;
  font-weight: 500;
  line-height: 1;
  position: relative;
  cursor: pointer;
  display: inline-block;
  white-space: nowrap;
  outline: none;
  font-size: 14px;
  margin-right: 30px;
  -moz-user-select: none;
  -webkit-user-select: none;
  display: flex;
}

::v-deep .el-radio__label {
  font-size: 14px;
  padding-left: 10px;
  position: relative;
  top: -10px;
}
</style>
